import { useModel } from "umi";
import { useReactive } from "ahooks";
import { useEffect } from "react";

import { AllOrganizationApplicationCustomers, AllOrganizationApplicationAuthorizedRolesByOiUuid, AllOrganizationApplicationAuthorizedRecordsByOiUuid } from "../_graphql/customer";

const useOrganizationCustomer = () => {
    const { graphqlFetchPlatform } = useModel("global");

    const state = useReactive({
        dataLoading: false,
        submitLoading: false,
        customers: [],
        totalCount: 0,
        selectedCustomer: {},
        authorizeRoles: [],
        authorizeRecords: [],
    });

    const loadCustomers = async () => {
        state.dataLoading = true;
        let res = await graphqlFetchPlatform({ query: AllOrganizationApplicationCustomers, variables: {} });
        let customers = res?.a?.nodes.map((item) => ({ ...item, ...item.customer })) || [];
        state.customers = helper.sortByKey(customers, "oiPyin", true);
        state.totalCount = res?.a?.totalCount || 0;
        state.dataLoading = false;
    };

    useEffect(() => {
        if (state.customers.length > 0) {
            state.selectedCustomer = state.customers.find((item) => item.oiUuid === state.selectedCustomer.oiUuid);
            !state.selectedCustomer && (state.selectedCustomer = state.customers[0]);
        }
    }, [state.customers]);

    const setSelectedCustomer = (data) => (state.selectedCustomer = data);

    const loadAuthorizeRoles = async (oiUuid) => {
        state.dataLoading = true;
        let res = await graphqlFetchPlatform({ query: AllOrganizationApplicationAuthorizedRolesByOiUuid, variables: { oiUuid } });
        state.authorizeRoles = res?.a?.nodes.map((item) => ({ ...item, ...item.servicer })) || [];
        state.totalCount = res?.a?.totalCount || 0;
        state.dataLoading = false;
    };

    const loadAuthorizeRecords = async (oiUuid) => {
        state.dataLoading = true;
        let res = await graphqlFetchPlatform({ query: AllOrganizationApplicationAuthorizedRecordsByOiUuid, variables: { oiUuid, oaaaExst: "已审核" } });
        state.authorizeRecords = res?.a?.nodes.map((item) => ({ ...item, ...item.servicer })) || [];
        state.totalCount = res?.a?.totalCount || 0;
        state.dataLoading = false;
    };

    return { ...state, loadCustomers, setSelectedCustomer, loadAuthorizeRoles, loadAuthorizeRecords };
};

export default useOrganizationCustomer;
